package com.hmdp.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.service.IUserInfoService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;
@Resource
private StringRedisTemplate stringRedisTemplate;
    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        // TODO 发送短信验证码并保存验证码
        System.out.println(phone);
        System.out.println(RegexUtils.isPhoneInvalid(phone));
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号不合法");
        }

        String code = RandomUtil.randomNumbers(6);
        session.setAttribute("code", code);
        return Result.ok(code);
    }

    /**
     * 登录功能
     *
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号不正确");
        }
        String code = (String) session.getAttribute("code");

            if (!code.equals(loginForm.getCode())||code == null) {
                return Result.fail("验证码错误");
            }

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, loginForm.getPhone());
        User user = userService.getOne(lambdaQueryWrapper);
        if (null == user) {
          user=  createphone(loginForm);

        }
//        session.setAttribute("user", BeanUtil.copyProperties(user,UserDTO.class));
String token= UUID.randomUUID().toString();
UserDTO userDTO=BeanUtil.copyProperties(user,UserDTO.class);
//user对象转为HashMap存储
        Map<String,Object> usermap=BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue)->fieldValue.toString()));
        //存储
        String tokenKey=LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,usermap);
        //设置有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        // TODO 实现登录功能
        return Result.ok(token);
    }
    public User createphone(LoginFormDTO loginForm){
        User user1 = new User();
        user1.setPhone(loginForm.getPhone());
        user1.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        user1.setCreateTime(LocalDateTime.now());
        user1.setUpdateTime(LocalDateTime.now());

        userService.save(user1);
        return user1;
    }

    /**
     * 登出功能
     *
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout() {

        // TODO 实现登出功能
        return Result.ok();
    }
@GetMapping("/{id}")
public Result queryUserById(@PathVariable("id") Long userId){
        User user=userService.getById(userId);
        if(user == null){
            return Result.ok();
        }
        UserDTO userDTO=BeanUtil.copyProperties(user,UserDTO.class);
        return Result.ok(userDTO);
}

    @GetMapping("/me")
    public Result me(HttpSession httpSession) {
        // TODO 获取当前登录的用户并返回
        UserDTO user= UserHolder.getUser();
        System.out.println(user);
        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId) {
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }
    @GetMapping("/sign/count")
    public Result signCount(){
        return userService.signCount();
    }
    @PostMapping("/sign")
    public Result sign(){
        return userService.sign();
    }
}
